//
//  MainViewController.swift
//  Residual_memmem
//
//  Created by 武振磊 on 16/7/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    // 按钮点击事件
    @objc private func click(){
        print("点我了")
    }
    
    //MARK:   生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        addComposedButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedButton)
    }
    
    // 懒加载撰写按钮
    private lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add_highlighted", backImageName: "tabbar_compose_button")
}

//MARK: 添加各个控制器、撰写按钮
extension MainViewController{
    
    /// 添加撰写按钮
    private func addComposedButton(){
        
        tabBar.addSubview(composedButton)
        
        let width = tabBar.bounds.width
        
        let count = childViewControllers.count
        
        let w = width / CGFloat (count) - 1
        //设定按钮的位置 CGRectInset
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        composedButton.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    ///    添加控制器
    private func addChildViewControllers() {
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoveryTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    ///   添加控制器方法的抽取
    ///
    ///   - parameter vc:        vc
    ///   - parameter title:     title
    ///   - parameter imageName: imageName
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        //经典的架构，TabbarC -> NavC -> VC，设置标题，由内至外
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)

    }
    
    ///   添加一个控制器，函数重载（函数的参数个数和类型不同）
    private func addChildViewController() {
        let vc = HomeTableViewController()
        vc.title = "首页"
        vc.tabBarItem.image = UIImage(named: "tabbar_home")
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}